package THYTHM;

import common.EventType;
import common.GameEvent;
import common.JavaGame;
import common.Music;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.input.*;
import javafx.scene.text.Font;
import javafx.scene.paint.Color;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ThyThm {
    private JavaGame game;
    private Font font;
    private List<Image> images;
    private List<Image> BeginImages;
    private List<Image> LoadingImages;
    private final List<Image> covers;
    private Image logo; // Logo图片（缩小版）
    private int index = 0;

    private int width;
    private int height;

    private boolean isResourcesLoaded = false; // 资源是否加载完成
    private boolean isLoadingImagesLoaded = false; // 加载动画资源是否加载完成
    private boolean isBeginImagesLoaded = false; // 入场动画资源是否加载完成

    private Music backgroundMusic;
    public ThyThm() {
        images = new ArrayList<>();
        BeginImages = new ArrayList<>();
        LoadingImages = new ArrayList<>();
        covers = new ArrayList<>();
    }
    public void run() {
        begin();
        game.drawRect(0, 0, width, height, Color.WHITE);

        while (true) {
            List<GameEvent> events = game.getEvents();
            for (GameEvent event : events) {
                if(event.type == EventType.MOUSE_CLICK){
                    System.out.println("点击了鼠标");
                    MouseEvent mouseEvent = (MouseEvent) event.source;
                    if(mouseEvent.getButton() == MouseButton.PRIMARY){
                        index = (index + 1) % images.size();
                    }
                    else {
                        index = (index - 1 + images.size()) % images.size();
                    }
                    game.blit(images.get(index), 0, 0);
//                    game.drawText("点击了鼠标", 0, 20, Color.RED, font);
                }
            }

            // 避免 CPU 占用过高
            try {
//                game.clear();
                Thread.sleep(100); // 每 10ms 检查一次事件
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }

            game.update();
        }
    }

    private void begin() {
        // 等待入场动画资源加载完成（最多等10秒，避免无限阻塞）
        long startWait = System.currentTimeMillis();
        while (!isBeginImagesLoaded) {
            if (System.currentTimeMillis() - startWait > 10000) { // 10秒超时
                System.err.println("入场资源加载超时！");
                return;
            }
            try {
                Thread.sleep(100); // 每100ms检查一次
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }

        // 播放入场动画
        for (int i = 0; i < BeginImages.size(); i++) {
            game.clear(); // 清空上一帧
            game.blit(BeginImages.get(i), 0, 0);
            game.update(); // 刷新屏幕

            // 特殊帧停留3秒，其他帧按30ms间隔播放
            if (i == 0 || i == 14 || i == 27) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            } else {
                try {
                    Thread.sleep(30); // 普通帧间隔
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        }

        backgroundMusic.play(-1);

        // 等待加载动画资源加载完成（最多等10秒，避免无限阻塞）
        startWait = System.currentTimeMillis();
        while (!isLoadingImagesLoaded) {
            if (System.currentTimeMillis() - startWait > 10000) { // 10秒超时
                System.err.println("加载动画资源加载超时！");
                return;
            }
            try {
                Thread.sleep(100); // 每100ms检查一次
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
        // 等待所有游戏资源加载完成后再进入主循环
        double cnt = 0;

        while (!isResourcesLoaded) {
            // 循环显示加载动画
            try {
                for (int i = 0; i < LoadingImages.size(); i++) {
                    cnt+=0.001;
                    if(cnt>=1){
                        cnt = 0.99;
                    }
                    game.clear();;
                    game.blit(LoadingImages.get(i), 0, 0);

                    drawLaodingBar(cnt);

                    game.update(); // 刷新屏幕
                    game.tick(30);

                    if (isResourcesLoaded) {
                        cnt = 1;
                        drawLaodingBar(cnt);
                        game.update(); // 刷新屏幕

                        break; // 资源加载完成，退出循环
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void drawLaodingBar(double cnt) {
        // 进度条参数：居中显示，宽度为屏幕的40%，高度为屏幕的1.5%
        double barWidth = width * 0.8;  // 进度条宽度（屏幕的40%）
        double barHeight = height * 0.015;  // 进度条高度（屏幕的1.5%）
        
        // 确保居中：使用屏幕中心点计算
        double centerX = width / 2.0;  // 屏幕中心X坐标
        double barX = centerX - barWidth / 2.0;  // 进度条左边缘 = 中心 - 一半宽度
        double barY = height * 0.95;  // 距离底部5%的位置
        
        // 确保不超出屏幕边界
        if (barX < 0) barX = 0;
        if (barX + barWidth > width) {
            barX = Math.max(0, width - barWidth);
        }
        
        // 绘制进度条背景（深灰色，带圆角效果）
        double cornerRadius = barHeight / 2;  // 圆角半径
        // 使用web方法创建颜色，格式为 #RRGGBB
        Color bgColor = Color.web("#282828");  // 深灰色背景
        game.drawRoundedRect(barX, barY, barWidth, barHeight, cornerRadius, bgColor);
        
        // 绘制进度条前景（渐变色效果，从蓝色到紫色）
        double progressWidth = barWidth * cnt;
        if (progressWidth > 0) {
            // 使用渐变色：从蓝色到紫色，确保值在0-255范围内
            int r = Math.min(255, Math.max(0, (int)(100 + cnt * 155)));
            int g = Math.min(255, Math.max(0, (int)(150 + cnt * 105)));
            int b = 255;
            // 使用正确的十六进制格式 #RRGGBB
            String colorHex = String.format("#%02X%02X%02X", r, g, b);
            Color progressColor = Color.web(colorHex);
            game.drawRoundedRect(barX, barY, progressWidth, barHeight, cornerRadius, progressColor);
            
            // 添加高光效果（顶部白色半透明条）- 使用带透明度的格式
            Color highlightColor = Color.web("#FFFFFF4D");  // 白色，30%透明度 (4D = 77/255 ≈ 0.3)
            game.drawRoundedRect(barX, barY, progressWidth, barHeight * 0.3, cornerRadius, highlightColor);
        }
        
        // 绘制Logo装饰（在进度条左侧）
        if (logo != null) {
            double logoSize = barHeight * 2.5;  // Logo大小为进度条高度的2.5倍
            double logoX = barX - logoSize - barHeight * 2;  // Logo在进度条左侧，留出间距
            double logoY = barY - (logoSize - barHeight) / 2;  // Logo垂直居中
            
            game.blit(logo, progressWidth + barX, logoY);
        }
        
        // 绘制进度百分比文字（在进度条右侧）
        String percentText = String.format("%.0f%%", cnt * 100);
        double textX = barX + barWidth + barHeight * 2;
        double textY = barY + barHeight * 0.7;
        game.drawText(percentText, textX, textY, Color.WHITE, font);
    }

    private void load() {
        // 1. 加载字体（同步，较快）
        loadFont();
        
        // 1.5. 加载Logo（同步，较小图片）
        loadLogo();

        // 2. 异步加载资源（使用线程池）
        ExecutorService executor = Executors.newFixedThreadPool(4);

        // 阶段1：先加载入场动画资源（BeginImages）
        executor.submit(() -> {
            try {
                List<Path> beginPaths = Files.walk(Paths.get("src/resource/begin"))
                        .filter(Files::isRegularFile)
                        .toList();

                for (Path path : beginPaths) {
                    Image img = game.loadImage(path.toString(), width, height);
                    if (!img.isError()) {
                        synchronized (BeginImages) {
                            BeginImages.add(img);
                        }
                    }
                }
                isBeginImagesLoaded = true; // 入场资源加载完成
                System.out.println("入场动画资源加载完成，共 " + BeginImages.size() + " 张");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 阶段2：加载加载动画资源（LoadingImages）
        executor.submit(()->{
            try {
                List<Path> loadingPaths = Files.walk(Paths.get("src/resource/loading"))
                        .filter(Files::isRegularFile)
                        .toList();

                for (Path path : loadingPaths) {
//                    System.out.println("加载加载动画资源：" + path.getFileName());
                    Image img = game.loadImage(path.toString(), width, height);
                    if (!img.isError()) {
                        synchronized (LoadingImages) {
                            LoadingImages.add(img);
                        }
                    }
                }
                isLoadingImagesLoaded = true; // 加载动画资源加载完成
                System.out.println("加载动画资源加载完成，共 " + LoadingImages.size() + " 张");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        // 阶段3：加载游戏主资源（images）
        executor.submit(() -> {
            try {
                List<Path> imagesPaths = Files.walk(Paths.get("src/resource/MusicGameResource/gameImage"))
                        .filter(Files::isRegularFile)
                        .toList();

                for (Path path : imagesPaths) {
                    Image img = game.loadImage(path.toString(), width, height);
                    if (!img.isError()) {
                        synchronized (images) {
                            images.add(img);
                        }
                    }
                }

                List<Path> colorsPaths = Files.walk(Paths.get("src/resource/MusicGameResource/gameCover"))
                        .filter(Files::isRegularFile)
                        .toList();

                for (Path path : colorsPaths) {
                    Image img = game.loadImage(path.toString(), width/2, height/2);
                    if (!img.isError()) {
                        synchronized (covers) {
                            covers.add(img);
                        }
                    }
                }

                isResourcesLoaded = true; // 所有资源加载完成
                System.out.println("游戏主资源加载完成，共 " + images.size() + covers.size() + " 张");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 关闭线程池（不阻塞）
        executor.shutdown();
    }

    // 提取加载字体的方法
    private void loadFont() {
        try (InputStream fontStream = new FileInputStream("src\\resource\\font\\THYTHM.ttf")) {
            font = Font.loadFont(fontStream, 15);
        } catch (Exception e) {
            throw new RuntimeException("字体加载失败：" + e.getMessage(), e);
        }
    }
    
    // 提取加载Logo的方法
    private void loadLogo() {
        try {
            // 加载原始logo图片（Image构造函数可以在后台线程调用）
            Image originalLogo = game.loadImage("src/resource/image/icon.png", width, height);
            if (originalLogo != null && !originalLogo.isError()) {
                // 将logo缩小到合适的大小（约为屏幕高度的5%）
                int logoSize = (int)(height * 0.02);
                // resizeImage需要在FX线程上执行，使用Platform.runLater
                // 使用CountDownLatch来等待FX线程完成
                java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1);
                Platform.runLater(() -> {
                    try {
                        logo = game.resizeImage(originalLogo, logoSize, logoSize);
                    } catch (Exception e) {
                        System.err.println("Logo缩放失败：" + e.getMessage());
                        logo = null;
                    } finally {
                        latch.countDown();
                    }
                });
                // 等待FX线程完成（最多等待1秒）
                try {
                    latch.await(1, java.util.concurrent.TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    logo = null;
                }
            }
        } catch (Exception e) {
            System.err.println("Logo加载失败：" + e.getMessage());
            logo = null; // 如果加载失败，设置为null，进度条会跳过logo绘制
        }
    }

    public void init() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int width = (int) screenSize.getWidth();
        int height = (int) screenSize.getHeight();
        this.width = width;
        this.height = height;
        JavaGame.startGame(JavaGame.class, width, height, "THYTHM");
        this.game = JavaGame.getInstance();
        this.game.disableWindowDragging();


        game.setWindowIcon("src/resource/image/icon.png");

        backgroundMusic = new Music("src/resource/MusicGameResource/pianocd - 星河.mp3");

        load();
    }
}
